<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Editor from './Editor.vue';
import { TableData } from './models/Table';

//Editor.vue不能单独运作，需要父级组件传入数据和接收保存数据
//本文件用于模拟真正的父级组件

var mode:"passIn" | "loadAsync" = 'passIn';
const fetchTime = 100;

const data: TableData = {
    id: 0, name: "testTable",
    cells:
        [
            ["乘法口诀表（节选）", "", "", "", ""],
            ["1x1", "1x2", "1x3", "1x4", "1x5"], ["", "2x2", "2x3", "2x4", "2x5"],
            ["", "", "3x3", "3x4", "3x5"], ["", "", "", "4x4", "4x5"], ["", "", "", "", "5x5"]
        ],
    merges: [{ row: 0, col: 0, right: 4, down: 0 }],
    colors:[{pos:[0,0], bg:'#6495ed', text:'#ffffff'}],
    sticky:{
        topIdx:2,
        leftIdx:1,
        leftFromRowIdx:2
    }
}

//直接传递数据给编辑器
const tableDemoData1 = ref<TableData>()

//通过ref调用函数传入数据
var tableDemoData2:TableData = data;
const tableEditor = ref<InstanceType<typeof Editor>>();

async function doSthWithDataToSave(data:TableData,callBack:(success:boolean,msg:string)=>void){
    //模拟用api保存数据，可检查合法性
    setTimeout(()=>{
        if(data.cells.length>2){
            console.log(data);
            callBack(true,"此处为体验环境，无保存功能");
        }
        else{
            callBack(false,"表格过小，不允许保存")
        }
    }, 500)
}

function changedHandler(){
    //数据发生了变动，保存前应该阻止用户离开或刷新页面
    console.log("data changed")
}
function sizeChangedHandler(data:{height:number}){
    console.log(data.height);
}

let activeSaveFn:(()=>Promise<boolean>)|undefined;
function setExternalSaveCallback(save:()=>Promise<boolean>){
    activeSaveFn = save;
}

onMounted(() => {
    //模拟从服务器取得数据
    setTimeout(() => {
        if(mode=='passIn'){
            tableDemoData1.value = data
        }
        else if(mode=='loadAsync'){
            tableEditor.value?.loadData(tableDemoData2);
        }
    },fetchTime)

    setTimeout(async()=>{
        await tryActiveSave();
    }, 1000)
})
async function tryActiveSave() {
    if (activeSaveFn) {
        const success = await activeSaveFn()
        if (success) {
            console.log("主动调用保存成功")
        } else {
            console.log("主动调用保存失败")
        }
    }
}
</script>

<template>
    <!-- 法一: 使用v-if使**数据取到后再**显示组件，“加载中”提示另外解决 -->
    <Editor v-if="mode=='passIn' && tableDemoData1" :table-data="tableDemoData1" 
        @save="doSthWithDataToSave" 
        :no-ads="false" @changed="changedHandler" 
        :size-change-callback="sizeChangedHandler" :no-shortcut="false" :external-save-callback-provide="setExternalSaveCallback"></Editor>

    <!-- 法二: 数据加载完后通过[ref].loadData(data)传入 -->
    <!-- 引用npm包时，InstanceType<typeof Editor>会失效，不能使用 -->
    <Editor v-if="mode=='loadAsync'" ref="tableEditor" @save="doSthWithDataToSave" :no-ads="false" @changed="changedHandler" :external-save-callback-provide="setExternalSaveCallback"></Editor>

    <button style="position: fixed; left:0px; bottom: 0px;" @click="tryActiveSave">外部主动保存（测试用）</button>
</template>